<template>
  <div class="relative">
    <!-- 平台信息头部 -->
    <div class="platform-header group">
      <!-- 主要信息区域 -->
      <div class="p-6 rounded-lg transition-all duration-300">
        <div class="flex items-start gap-6">
          <!-- 平台图标 -->
          <div class="flex-shrink-0">
            <el-image :src="logo" class="w-20 h-20 rounded-full border-2" style="border-color: var(--el-border-color-light)" fit="cover">
              <template #error>
                <div class="w-20 h-20 rounded-full flex items-center justify-center" style="background-color: var(--el-fill-color-light)">
                  <el-icon class="text-2xl" style="color: var(--el-text-color-placeholder)"><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <!-- 平台详情 -->
          <div class="flex-1 min-w-0">
            <div class="flex items-center justify-between mb-3">
              <h3 class="text-xl font-semibold truncate" style="color: var(--el-text-color-primary)">
                {{ platform.name || '未命名平台' }}
              </h3>
              <el-button type="info" size="small" @click="onGoBack">
                <el-icon><ArrowLeft /></el-icon>
                返回列表
              </el-button>
            </div>

            <div class="space-y-2">
              <div class="flex items-center gap-2">
                <el-tag type="primary" size="small">{{ platform.type_name || '未知类型' }}</el-tag>
                <el-tag :type="getStatusType(platform.status)" size="small">
                  {{ getStatusText(platform.status) }}
                </el-tag>
              </div>
              <p class="text-sm leading-relaxed" style="color: var(--el-text-color-regular)">
                {{ platform.description || '暂无描述' }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div v-permission="['all']" class="action-panel bottom-0 left-0 right-0 p-4" style="background-color: var(--el-bg-color-page)">
        <div class="flex items-center justify-between">
          <span class="text-sm font-medium" style="color: var(--el-text-color-regular)">平台操作</span>
          <div class="flex items-center gap-2">
            <!-- 自定义操作插槽 -->
            <slot name="action" />

            <!-- 编辑按钮 -->
            <el-button type="primary" size="small" @click="onEdit">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>

            <!-- 子账号按钮 -->
            <el-button type="info" size="small" @click="onShowPermissions">
              <el-icon><User /></el-icon>
              子账号
            </el-button>

            <!-- 状态切换按钮 -->
            <el-button v-if="platform.status === 1" type="warning" size="small" @click="onStatusChange">
              <el-icon><VideoPause /></el-icon>
              停用
            </el-button>
            <el-button v-else type="success" size="small" @click="onStatusChange">
              <el-icon><VideoPlay /></el-icon>
              启用
            </el-button>

            <!-- 删除按钮 -->
            <el-button type="danger" size="small" @click="onDelete">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 子账号对话框 -->
    <el-dialog v-model="dialogPermissionVisible" title="子账号管理" width="800px" class="max-w-90vw" append-to-body :z-index="999">
      <permission-list />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, defineOptions } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, ArrowLeft, Edit, User, VideoPause, VideoPlay, Delete } from '@element-plus/icons-vue'
import { changePlatformStatus, deletePlatform } from '@/api/platform'
import PermissionList from '@/views/platform/components/common/PermissionList/PermissionList.vue'

defineOptions({
  name: 'HeaderManage'
})

// Props定义
const props = defineProps({
  platform: {
    type: Object,
    default: () => ({})
  },
  formData: {
    type: Object,
    default: null
  }
})

// Emits定义
const emit = defineEmits(['edit', 'submit'])

// 响应式数据
const router = useRouter()
const dialogPermissionVisible = ref(false)

// 计算属性
const logo = computed(() => {
  return props.platform.logo || new URL('@/assets/default/default.png', import.meta.url).href
})

// 获取状态类型
function getStatusType(status) {
  const statusMap = {
    0: 'danger', // 停用
    1: 'success' // 启用
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    0: '已停用',
    1: '运行中'
  }
  return statusMap[status] || '未知状态'
}

// 返回列表
function onGoBack() {
  router.push({ path: '/customer' })
}

// 编辑平台
function onEdit() {
  emit('edit')
}

// 显示子账号管理
function onShowPermissions() {
  dialogPermissionVisible.value = true
}

// 改变平台状态
function onStatusChange() {
  const statusText = props.platform.status === 1 ? '停用' : '启用'
  const confirmText = `确定要${statusText}平台"${props.platform.name}"吗？`

  ElMessageBox.confirm(confirmText, '状态变更确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      changePlatformStatus(props.platform.plaid)
        .then((res) => {
          ElMessage.success(res.msg || `${statusText}成功`)
          onSubmit()
        })
        .catch((error) => {
          ElMessage.error(error.message || `${statusText}失败`)
        })
    })
    .catch(() => {
      ElMessage.info('已取消操作')
    })
}

// 删除平台
function onDelete() {
  ElMessageBox.confirm(`此操作将永久删除平台"${props.platform.name}"，所有相关数据将无法恢复！`, '删除确认', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'error',
    dangerouslyUseHTMLString: true,
    message: `
        <div style="margin: 16px 0;">
          <p><strong>警告：此操作不可逆！</strong></p>
          <p>删除后将清除以下数据：</p>
          <ul style="margin: 8px 0; padding-left: 20px;">
            <li>平台基本信息</li>
            <li>子账号权限配置</li>
            <li>相关业务数据</li>
          </ul>
          <p style="color: #f56c6c;">请确认您真的要删除平台"${props.platform.name}"？</p>
        </div>
      `
  })
    .then(() => {
      deletePlatform(props.platform.plaid)
        .then((res) => {
          ElMessage.success(res.msg || '删除成功')
          onSubmit()
        })
        .catch((error) => {
          ElMessage.error(error.message || '删除失败')
        })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 提交事件
function onSubmit() {
  emit('submit')
}
</script>
<style scoped lang="scss">
// 平台头部样式
.platform-header {
  position: relative;
  background: var(--el-bg-color);
  border-radius: 10px;
  transition: all 0.3s ease-in-out;

  // 操作面板样式
  .action-panel {
    z-index: 10;
    border-radius: 10px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    opacity: 0;
    position: absolute;
    transition: all 0.3s ease-in-out;
    bottom: -10px;
  }
  &:hover {
    box-shadow: var(--dk-header-manage-box-shadow);
    background: var(--el-bg-color-page);
    .action-panel {
      opacity: 1;
      bottom: -35px;
      box-shadow: var(--dk-header-manage-box-shadow);
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .platform-header {
    .action-panel {
      position: static !important;
      opacity: 1 !important;
      margin: 0;
      border-top: 1px solid var(--el-border-color-light);
      border-radius: 0 0 8px 8px;

      .flex {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;

        .flex:last-child {
          justify-content: center;
          flex-wrap: wrap;
        }
      }
    }
  }
}

// 对话框样式调整
:deep(.el-dialog) {
  @media (max-width: 768px) {
    width: 90% !important;
    margin: 5vh auto;
  }
}
</style>
